package com.orkasgb.framework.hadoop.mapperreduce.compress;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.compress.BZip2Codec;
import org.apache.hadoop.io.compress.CompressionCodec;
import org.apache.hadoop.io.compress.Lz4Codec;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.File;
import java.io.IOException;

public class CompressDriver {

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {

        Configuration configuration = new Configuration();
        // 设置wordcount计算时是否忽略大小写
        // configuration.setBoolean("wordcount.case.sensitive", true);
        // configuration.setBoolean("io.compression.codecs", true);

        // 设置map端文件的压缩形式。map端的文件压缩和最终文件的压缩形式互不影响
        configuration.setBoolean("mapreduce.map.output.compress", true);
        configuration.setClass("mapreduce.map.output.compress.codec", Lz4Codec.class, CompressionCodec.class);

        // 设置最终文件的压缩形式。
        configuration.setBoolean("mapreduce.output.fileoutputformat.compress", true);
        configuration.setClass("mapreduce.output.fileoutputformat.compress.codec", BZip2Codec.class, CompressionCodec.class);

        Job job = Job.getInstance(configuration);

        // 设置job名称
        job.setJobName("compress");

        job.setJarByClass(CompressDriver.class);

        // 指定Mapper和Reduce
        job.setMapperClass(CompressMapper.class);
        job.setReducerClass(CompressReduce.class);

        // 设置Mapper输出K/V类型
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        // F:\hadoop\input\wordcount\compress.txt F:\hadoop\input\wordcount\wordcount01.txt
        // 默认是TextInputFormat，按文件切片，按行读数据，切片数量为2，开启两个MapTask。
        // 对于大量小文件，CombineTextInputFormat，按照多个文件进行切片，切片数据为1，开启一个MapTask.
        // job.setInputFormatClass(CombineTextInputFormat.class);
        // job.setCombinerClass();
        job.setNumReduceTasks(2);

        // 设置最终输出K/V类型
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(LongWritable.class);

        FileUtils.deleteDirectory(new File("F:\\hadoop\\output\\compress"));

        // 指定输入输出文件
        FileInputFormat.setInputPaths(job, new Path("F:\\hadoop\\input\\compress\\compress.txt"));
        FileOutputFormat.setOutputPath(job, new Path("F:\\hadoop\\output\\compress"));

        final boolean wait = job.waitForCompletion(true);
        System.exit(wait ? 0 : 1);
    }
}
